{extend name="../../admin/view/main"}

{block name='content'}
<form  class="layui-form layui-card" submit="retrun false" name="menu" role="form"  id="MenuEditor">
    <div class="layui-card-body" >

        <div class="layui-row">
            <div class="layui-col-xs4">
                


                {notempty name='cateorys'}
                <div class="layui-form-item relative block">
                    <span class="color-green font-w7 label-required-prev">种类</span>
                    <select name="category" class="layui-select" required lay-search>
                        {foreach $cateorys as $k=>$v}
                        {if isset($vo.category) and $vo.category eq $v.code}
                        <option selected value="{$v.code}">{$v.name}</option>
                        {else}
                        <option value="{$v.code}">{$v.name}</option>
                        {/if}
                        {/foreach}
                    </select>
                </div>
                {/notempty}

                
                <!-- <label class="layui-form-item relative block " >
                    <span class="color-green font-w7">框数</span>
                    <input class="layui-input" name="box_num" type="number" placeholder="请输入" value='{$vo.box_num|default=""}'>
                </label> -->
                

                {notempty name='warehouses'}
                <div class="layui-form-item relative block">
                    <span class="color-green font-w7 label-required-prev">客户</span>
                    <select name="depart_code" class="layui-select" required lay-search>
                        <option value="">请选择</option>
                        {foreach $warehouses as $k=>$v}
                        {if isset($vo.depart_code) and $vo.depart_code eq $v.ware_code}
                        <option selected value="{$v.ware_code}">{$v.ware_name}</option>
                        {else}
                        <option  value="{$v.ware_code}">{$v.ware_name}</option>
                        {/if}
                        {/foreach}
                    </select>
                </div>
                {/notempty}

              

                {notempty name='warehouses'}
                <div class="layui-form-item relative block">
                    <span class="color-green font-w7 label-required-prev">目的地仓库</span>
                    <select name="receiver_code" class="layui-select" required lay-search>
                        <option value="">请选择</option>
                        {foreach $warehouses as $k=>$v}
                        {if isset($vo.receiver_code) and $vo.receiver_code eq $v.ware_code}
                        <option selected value="{$v.ware_code}">{$v.ware_name}</option>
                        {else}
                        <option  value="{$v.ware_code}">{$v.ware_name}</option>
                        {/if}
                        {/foreach}
                    </select>
                </div>
                {/notempty}

                <label class="layui-form-item relative block">
                    <span class="color-green font-w7">车牌号</span>
                    <input class="layui-input" name="car_number" type="text" placeholder="请输入" 
                        value='{$vo.car_number|default=""}'>
                </label>


                <label class="layui-form-item relative block">
                    <span class="color-green font-w7">备注</span>
                    <textarea class="layui-textarea" name="remark" placeholder="请输入"
                        >{$vo.remark|default=''}</textarea>
                </label>
            </div>
            <div class="layui-col-xs8">
                <div class="grid-demo" style="margin-left: 20px;">
                    

                    <table class="layui-table">
                        <colgroup>
                            <col width="100">
                            <col width="100">
                            <col width="100">
                            <col width="150">
                            <col width="100">
                            <col width="150">
                        </colgroup>
                        <thead>
                            <tr>
                                <th>等级</th>
                                <th>重量(斤)</th>
                                <th>件数</th>
                                <th>散件重量</th>
                                <th>总重</th>
                                <th>价格(¥)</th>
                                <th>金额(¥)</th>
                               
                            </tr>
                        </thead>
                        <tbody>

                            <tr ng-repeat="rows in levelsAll track by $index">
                                <td>
                                    {{rows.name}}
                                </td>
                                <td>
                                    <input class="layui-input" type="number" ng-change="calculate($index)"  ng-model="rows.weight" placeholder="重量" />
                                </td>
                                <td>
                                    <input class="layui-input" type="number" ng-change="calculate($index)" ng-model="rows.num"  placeholder="件数" />
                                </td>
                                <td>
                                    <input class="layui-input" type="number" ng-change="calculate($index)" ng-model="rows.other_weight" placeholder="重量" />
                                </td>
                                <td>
                                    <input class="layui-input" type="number" ng-model="rows.gross_weight"   placeholder="总重" />
                                </td>
                               
                                <td>
                                    <input class="layui-input" type="number" ng-change="calculate($index)" ng-model="rows.unit_price" placeholder="价格" />
                                </td>
                                <td>
                                    <input class="layui-input" type="number" ng-model="rows.price" placeholder="金额" />
                                </td>
                            </tr>
                          
                        </tbody>
                    </table>

                    
                </div>
            </div>
        </div>





        <div class="hr-line-dashed"></div>
        <label class="layui-hide">
            <textarea name="details">{{levelsAll}}</textarea>
        </label>
        {notempty name='vo.id'}<input name='id' type='hidden' value='{$vo.id}'>{/notempty}
        {notempty name='vo.bill_no'}<input name='bill_no' type='hidden' value='{$vo.bill_no}'>{/notempty}

        <div class="layui-form-item text-center">
            <button class="layui-btn" ng-click="submit()">保存数据</button>
            <button class="layui-btn layui-btn-danger" data-history-back data-confirm="确定要取消编辑吗？"
                type='button'>取消编辑</button>
        </div>
    </div>

</form>


<label class="layui-hide">
    {if isset($details)}
    <textarea id="levels">{$details|raw|default=''}</textarea>
    {else}
    <textarea id="levels">{$levels|raw|default=''}</textarea>
    {/if}
</label>
<script>
    require(['angular'], function () {

        var vali = this, app = angular.module('MenuEditor', []).run(callback);
            angular.bootstrap(document.getElementById(app.name), [app.name]);

            function callback($rootScope) {
                $rootScope.levels = Object.values(angular.fromJson(angular.element('#levels').val() || '[]') || []);
                $rootScope.item = {}, $rootScope.list = [], $rootScope.keys = [];
                // $.form.load('{:request()->url()}', {output: 'json'}, 'get', function (ret) {
                //     $rootScope.$apply(function () {
                //         $rootScope.keys = ret.data.keysdata || [], $rootScope.list = ret.data.menudata || [];
                //         if ($rootScope.list.length < 1) $rootScope.list = [{name: '请输入名称', type: 'click', sub_button: []}];
                //         for (var i in $rootScope.list) $rootScope.list[i].sub_button = $rootScope.list[i].sub_button || [];
                //         $rootScope.list[0].show = true, $rootScope.list[0].active = true, $rootScope.item = $rootScope.list[0];
                //     });
                //     return false;
                // });
               
                 // 初始化分类
                $rootScope.initLevels = function() {
                    $rootScope.levelsAll = [];
                    console.log($rootScope.levels)
                    for(let i=0; i<$rootScope.levels.length; i++) {
                        $rootScope.levelsAll.push({
                            name: $rootScope.levels[i].name,
                            weight: 0,
                            num: 0,
                            other_weight: 0,
                            gross_weight: 0,
                            unit_price: 0,
                            price: 0
                        });
                    }
                };
                $rootScope.initLevels();

                // 提交数据
                $rootScope.submit = function() {
                    const data = {
                        levels: $rootScope.levelsAll,
                        total: $rootScope.totalAmount
                    };

                    console.log(data)
                    
                    // 发送到后端
                    // layui.jquery.post('{:sysuri()}', data, function(res) {
                    //     layer.msg(res.msg, { icon: res.code === 200 ? 1 : 2 });
                    // });
                };

                    // 计算单级数据
                $rootScope.calculate = function(index) {
                    const level = $rootScope.levelsAll[index];
                    // 计算总重量（件数*420 + 散件）
                    level.gross_weight = level.weight * level.num + level.other_weight;
                    
                    level.price = level.gross_weight * level.unit_price;
                    
                    // 更新总金额
                    //$rootScope.updateTotal();
                };
                
                // 更新总金额
                $rootScope.updateTotal = function() {
                    $rootScope.totalAmount = $rootScope.levels.reduce((sum, level) => {
                        return sum + parseFloat(level.amount || 0);
                    }, 0).toFixed(2);
                };
                
               
                // 动态计算宽度
                $rootScope.getItemStyle = function (list) {
                    return 'width:' + (100 / (list.length >= 3 ? 3 : (list.length + 1))) + '%';
                };

                // 增加菜单选项
                $rootScope.addItem = function (list) {
                    if (!vali.checkAllInput()) return;
                    list.push({name: '请输入名称', type: 'click', sub_button: []});
                };

                // 移除菜单
                $rootScope.delItem = function (one, two) {
                    var tmp = [], _two = null;
                    if (two) {
                        for (var i in one.sub_button) if (one.sub_button[i] !== two) {
                            tmp.push(one.sub_button[i]);
                            if (one.sub_button[i].active) _two = one.sub_button[i];
                        }
                        one.sub_button = tmp;
                        return $rootScope.setActiveItem(one, _two, true);
                    }
                    for (var i in $rootScope.list) if (one !== $rootScope.list[i]) tmp.push($rootScope.list[i]);
                    $rootScope.list = tmp;
                    if ($rootScope.list.length > 1) $rootScope.setActiveItem($rootScope.list[0], null, false)
                };

                // 切换选择菜单
                $rootScope.setActiveItem = function (one, two, force) {
                    if (!force && !vali.checkAllInput()) return;
                    $rootScope.list.forEach(function (item) {
                        item.show = item === one;
                        item.active = two ? false : (item === one)
                        item.sub_button.forEach(function (subitem) {
                            subitem.active = subitem === two;
                        });
                    });
                    $rootScope.item = two || one || {};
                    $rootScope.item.type = $rootScope.item.type || 'click';
                    $rootScope.item.type === 'click' && syncActiveItem();
                };

                // 列表处理
                $rootScope.$watch('item', function () {
                    $rootScope.item.type === 'click' && syncActiveItem();
                }, true);

                // 提交数据
                $rootScope.submit = function () {
                    if (!vali.checkAllInput()) return false;
                    $.form.load('{:url("push")}', {data: angular.toJson($rootScope.list)}, 'post');
                }

                // 同步选择项值
                function syncActiveItem() {
                    setTimeout(function () {
                        layui.form.render('select');
                        $rootScope.item.key = $('[lay-filter="key"]').val();
                    }, 50);
                }

                layui.form.on('select(key)', function (data) {
                    $rootScope.item.key = data.value;
                });
            }
        

       
    });
</script>
{/block}